<?php

class Rating extends Model {
	
	function Rating()
	{
		parent::Model();
	}

	function rate($array)
	{
		$this->db->trans_start();
		$query = $this->db->insert('Rating', $array);
		$subject = $array['Subject'];
		$rating = $array['Rating'];
		$b = $this->db->query('SELECT Rating, RateCount from Subject where Subject.SubjectName = ?', $subject);
		$a = $b->row_array();
		$count = $a['RateCount'];
		$oldRating = $a['Rating'];
		$newRating = ($rating + ($count * $oldRating))/($count + 1);
		$count = $count + 1;
		$array = array('RateCount'=>$count, 'Rating'=>$newRating);
		$this->db->where('SubjectName', $subject);
		$this->db->update('Subject', $array);	
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
		{ //error
			return false;
		}
		return true;
	}
}

?>
